//---------------------------------------------------------------------------------
// Copyright (c) 2011, Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//---------------------------------------------------------------------------------

namespace Microsoft.Samples.ServiceBus.WindowsPhoneChat.Commands
{
    using System;
    using System.Net;
    using Microsoft.Samples.ServiceBus;
    using Microsoft.Samples.ServiceBus.Messaging;
    using Microsoft.Samples.ServiceBus.WindowsPhoneChat.Controllers;
    using Microsoft.Samples.ServiceBus.WindowsPhoneChat.ViewModels;

    public class GetSubscriptionCommand : Command<ChatTopicViewModel>
    {
        protected override bool CanExecute(ChatTopicViewModel viewModel)
        {
            return viewModel != null;
        }

        protected override void Execute(ChatTopicViewModel viewModel)
        {
            viewModel.TopicClient.BeginGetSubscription(App.Context.UserName, this.OnGetSubscriptionCompleted, viewModel);
        }

        private void OnGetSubscriptionCompleted(IAsyncResult result)
        {
            var viewModel = (ChatTopicViewModel)result.AsyncState;
            SubscriptionClient subscriptionClient = null;

            try
            {
                var subscription = viewModel.TopicClient.EndGetSubscription(result);
                subscriptionClient = new SubscriptionClient(subscription.TopicPath, subscription.Name, App.Context.TokenProvider);
            }
            catch (HttpWebException e)
            {
                // A 404 (Not Found) error indicates that the subscription does not exist
                if (e.StatusCode != HttpStatusCode.NotFound)
                {
                    throw;
                }
            }

            ViewController.Current.BeginInvokeUI(() => viewModel.SubscriptionClient = subscriptionClient);
        }
    }
}
